<template>
  <div v-if="store.dataSource && store.dataSource.length > 0">
    <a-form :model="formState" :label-col="{ style: { width: '120px' } }">
      <div v-for="(item, index) in formItem" :key="index">
        <a-form-item :label="item.label" class="w-full">
          <SelectTags
            v-model:value="formState[item.value]"
            :disabled="formState.status === 1"
            show-setting
            show-new
            multiple
            type="医嘱字典"
            :search-params="{ blcybh: item.label }"
            :input-or-textarea="false"
          />
        </a-form-item>
      </div>
      <a-form-item label="手术方案" class="w-full" :wrapper-col="{ span: 6, offset: 0 }">
        <a-upload
          :file-list="fileList"
          :disabled="formState.status === 1"
          accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
          :custom-request="beforeUpload"
          @remove="handleRemove"
          @preview="handlePreview"
        >
          <a-button :disabled="formState.status === 1"> 上传 </a-button>
        </a-upload>
      </a-form-item>
    </a-form>
    <div class="flex justify-end">
      <BaseButton v-if="formState.status === 1" confirm-text="确定撤销确认?" danger type="primary" @click="updateOperateStatus(0)"> 撤销确认 </BaseButton>
      <a-button v-else type="primary" @click="updateOperateStatus(1)">确认</a-button>
      <a-button type="primary" class="ml-2" :disabled="saveBtnState || formState.status === 1" @click="saveOperate">保存</a-button>
    </div>
  </div>
  <div v-else><a-empty /></div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import SelectTags from '@/components/SelectTags'
import { post } from '@/utils/request'
import download from '@/utils/download'
import useStore from '../store'

const store = useStore()
const formState = ref({})
const fileList = ref([])
const saveBtnState = ref(false)
const props = defineProps({
  patientData: {
    type: Object,
    default: () => ({})
  },
  selectedItem: {
    type: Object,
    default: () => ({})
  }
})
watch(
  () => props.patientData,
  (val) => {
    formState.value = { ...val }
    if (formState.value.oprProgramFileUrl) {
      fileList.value = [
        {
          uid: formState.value.oprProgramFile.length,
          name: formState.value.oprProgramFile,
          status: 'done',
          url: formState.value.oprProgramFileUrl
        }
      ]
    } else {
      fileList.value = []
    }
  }
)
watch(
  () => formState.value,
  (val) => {
    if (hasValue(val, formItem) || (fileList.value && fileList.value.length > 0)) {
      saveBtnState.value = false
    } else {
      saveBtnState.value = true
    }
  },
  {
    deep: true
  }
)
watch(
  () => fileList.value,
  (val) => {
    if (hasValue(formState.value, formItem) || (val && val.length > 0)) {
      saveBtnState.value = false
    } else {
      saveBtnState.value = true
    }
  },
  {
    deep: true
  }
)

const hasValue = (obj, keys) => {
  return keys.value.some(function (key) {
    return obj[key.value]
  })
}
const formItem = ref([
  {
    label: '术前处置描述',
    value: 'preoprDispose'
  },
  {
    label: '输液情况描述',
    value: 'infusion'
  },
  {
    label: '吸氧情况描述',
    value: 'oxygen'
  },
  {
    label: '患者准备情况',
    value: 'patientReady'
  },
  {
    label: '医护人员准备情况',
    value: 'staffReady'
  },
  {
    label: '药材准备情况',
    value: 'drugReady'
  },
  {
    label: '检查检验情况',
    value: 'risLisReady'
  },
  {
    label: '消毒准备',
    value: 'disinfectReady'
  },
  {
    label: '物资准备',
    value: 'supplyReady'
  },
  {
    label: '用血准备',
    value: 'bloodReady'
  },
  {
    label: '手术预报',
    value: 'oprPrediction'
  }
])
const beforeUpload = async (options) => {
  const { file } = options
  const isJpgOrPng = file.type === 'application/msword' || 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  if (!isJpgOrPng) {
    message.error('请上传Word格式文件!')
    fileList.value = fileList.value.filter((item) => {
      return !item.type
    })
    return
  }
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('上传文件最大10MB!')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  fileList.value = fileList.value.filter((item) => {
    return item.url
  })
  const { data: res } = await axios.post('/api/v1/common/util/doUploadFile', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = [
    {
      uid: fileList.value.length,
      name: file.name,
      status: 'done',
      url: res.data.picturePath
    }
  ]
  formState.value.oprProgramFile = file.name
  formState.value.oprProgramFileUrl = res.data.picturePath
}
const handlePreview = (file) => {
  download(file.url, file.name)
}
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file)
  const newFileList = fileList.value.slice()
  newFileList.splice(index, 1)
  fileList.value = newFileList
  formState.value.oprProgramFile = ''
  formState.value.oprProgramFileUrl = ''
}
const saveOperate = async () => {
  const { code, msg } = await post('/oprOperation/opr/doSavePreoperationReadyInfo', { oprLsh: props.selectedItem.oprLsh, ...formState.value })
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  store.refreshDetail = true
}
const updateOperateStatus = async (status) => {
  const { code, msg } = await post('/oprOperation/opr/doUpdatePreoperationReadyInfoStatus', { oprLsh: props.selectedItem.oprLsh, status })
  if (code !== 0) return message.error(msg)
  message.success(msg || '操作成功')
  store.refresh = true
}
</script>

<style lang="less" scoped></style>
